//
//  ShopViewController.m
//  iTaoHD
//
//  Created by liunian on 13-11-29.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "ShopViewController.h"
#import "ShopKey.h"
#import "DataManager.h"
#import "RefreshCell.h"
#import "LolayGridView.h"
#import "ShopCell.h"
#import "WebViewController.h"


#define kPortraitNum    4
#define kLandscapeNum    6
@interface ShopViewController ()<DataManagerDelegate,LolayGridViewDataSource,LolayGridViewDelegate,RefreshCellDelegate>{
    NSInteger   _index;
    BOOL        _reload;
    BOOL        _loadMore;
}
@property (nonatomic, strong) ShopKey *shopKey;

@property (nonatomic, retain) LolayGridView *gridView;
@property (nonatomic, retain) RefreshCell *headerCell;
@property (nonatomic, retain) RefreshCell   *footerCell;
@property (nonatomic, retain) NSMutableArray    *datasource;
@property (nonatomic, strong) UIImageView          *bottomImageView;
@property (nonatomic, retain) UIActivityIndicatorView *indicatorView;
@end

@implementation ShopViewController

- (id)initWithShopKey:(ShopKey *)shopKey
{
    self = [super init];
    if (self) {
        // Custom initialization
        self.shopKey = shopKey;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
}
#pragma mark -
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)tableViewDidScrollToTop{
    [self.gridView setContentOffset:CGPointMake(0, 0) animated:YES];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self bottomImageView];
    [self gridView];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    if (self.datasource.count == 0) {
        [self reloadItems];
    }
    
}

- (void)reloadItems{
    if (_reload) {
        return;
    }
    _index = 0;
    [self.indicatorView startAnimating];
    _reload = YES;
    [[DataManager sharedInstance] requestTBKShopItemsWithKeyword:self.shopKey.key WithPageIndex:_index withDelegate:self];
}
- (void)reloadMoreItems{
    
    if (_loadMore) {
        return;
    }
    [self.indicatorView startAnimating];
    _loadMore = YES;
    _index++;
    [[DataManager sharedInstance] requestTBKShopItemsWithKeyword:self.shopKey.key WithPageIndex:_index withDelegate:self];
    
}
#pragma mark  DataManagerDelegate
-(void) updateViewForSuccess:(id)dataModel{
    [self.indicatorView stopAnimating];
    NSMutableArray *items = dataModel;
    if (self.datasource.count == 0) {
        [self footerCell];
    }
    if (items && [items count]) {

        if (_reload) {
            _reload = NO;
            _index = 0;
            if ([items count] > 0) {
                [self.datasource removeAllObjects];
                [self.datasource addObjectsFromArray:items];
            }
        }
        
        if (_loadMore) {
            _loadMore = NO;
            [self.datasource addObjectsFromArray:items];
        }
        
        
        [self.gridView reloadData];
        [_footerCell refreshScrollViewDataSourceDidFinishedLoading:self.gridView];
        
    }else{
        [_footerCell refreshScrollViewDataSourceDidFinishedLoading:self.gridView];
        REMOVE_SAFELY(_footerCell);
    }
}
-(void) updateViewForError:(NSError *)errorInfo{
    [self.indicatorView stopAnimating];

    [_footerCell refreshScrollViewDataSourceDidFinishedLoading:self.gridView];
    
    if (_reload) {
        _reload = NO;
    }
    
    if (_loadMore) {
        _loadMore = NO;
        _index--;
    }
}

#pragma mark LolayGridViewDataSource
- (NSInteger)numberOfRowsInGridView:(LolayGridView*)gridView
{
    NSInteger count = [self.datasource count];
    int c = 4;
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (UIInterfaceOrientationIsPortrait(orientation)) {
        c = kPortraitNum;
        
    } else {
        c = kLandscapeNum;
    }
    
    return ceil(1.0f*count/c);
}
- (NSInteger)numberOfColumnsInGridView:(LolayGridView*)gridView
{
    int c = 4;
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (UIInterfaceOrientationIsPortrait(orientation)) {
        c = kPortraitNum;
    } else {
        c = kLandscapeNum;
    }
    
    return c;
}

- (LolayGridViewCell*)gridView:(LolayGridView*)gridView
                    cellForRow:(NSInteger)gridRowIndex
                      atColumn:(NSInteger)gridColumnIndex
{
    
    int c = kPortraitNum;
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (UIInterfaceOrientationIsPortrait(orientation)) {
        c = kPortraitNum;
    } else {
        c = kLandscapeNum;
    }
    
    NSInteger objectIndex = gridRowIndex * c + gridColumnIndex;
    if (objectIndex >= [self.datasource count]) {
        return nil;
    }
    
    static NSString *cellID = @"newsCell";
    ShopCell *cell = (ShopCell *)[gridView dequeueReusableGridCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[ShopCell alloc] initWithFrame:CGRectMake(0, 0, kShopCellWidth, kShopCellHeight) reuseIdentifier:cellID];
    }
    CuzyTBShopItem *item = (CuzyTBShopItem *)[self.datasource objectAtIndex:objectIndex];
    [cell setShopItem:item];
    return cell;
}

#pragma mark LolayGridViewDelegate
- (CGFloat)heightForGridViewRows:(LolayGridView*)gridView
{
    return kShopCellHeight;
}
- (CGFloat)widthForGridViewColumns:(LolayGridView*)gridView
{
    
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (UIInterfaceOrientationIsPortrait(orientation)) {
        return CGRectGetWidth(self.view.bounds) /kPortraitNum ;
    } else {
        return CGRectGetWidth(self.view.bounds) /kLandscapeNum ;;
    }
    return kShopCellWidth;
}
- (void)gridView:(LolayGridView*)gridView
didSelectCellAtRow:(NSInteger)gridRowIndex
        atColumn:(NSInteger)gridColumnIndex
{
    int c = kPortraitNum;
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (UIInterfaceOrientationIsPortrait(orientation)) {
        c = kPortraitNum;
    } else {
        c = kLandscapeNum;
    }
    
    NSInteger objectIndex = gridRowIndex*c + gridColumnIndex;

    CuzyTBShopItem *item = (CuzyTBShopItem *)[self.datasource objectAtIndex:objectIndex];
    NSString *shopURLStr = [NSString stringWithFormat:@"http://%@",item.shopClickUrl];
    WebViewController *webVC = [[WebViewController alloc] initWithURL:[NSURL URLWithString:shopURLStr]];
    [self.navigationController pushViewController:webVC animated:YES];
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_footerCell refreshScrollViewDidScroll:scrollView];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [_footerCell refreshScrollViewDidEndDragging:scrollView];
}

#pragma mark - RefreshCellDelegate
- (void)refreshCellDidTriggerLoading:(RefreshCell*)view{

        if (view == self.headerCell) {
            [self reloadItems];
        }else
            if (view == _footerCell) {
                [self reloadMoreItems];
            }

    
}

- (BOOL)refreshCellDataSourceIsLoading:(RefreshCell*)view{

    return self.headerCell.state == RefreshLoading || _footerCell.state==RefreshLoading;

}

- (NSDate*)refreshCellDataSourceLastUpdated:(RefreshCell*)view{
    return [NSDate date];
}

#pragma mark - getter
#pragma mark - getter
- (UIImageView *)bottomImageView{
    if (!_bottomImageView) {
        _bottomImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,
                                                                         CGRectGetHeight(self.view.bounds) - kDefaultBottomBarHeight -_kSpaceHeight,
                                                                         CGRectGetWidth(self.view.bounds),
                                                                         kDefaultBottomBarHeight)];
        _bottomImageView.backgroundColor = COLOR_RGB_BOTTOM;
        _bottomImageView.userInteractionEnabled = YES;
        
        UIImage *image = [IMGNAMED(@"bg_navback.png") resizableImageWithCapInsets:UIEdgeInsetsMake(2, 2, 2, 2)];
        [_bottomImageView setImage:image];
        
        UIImage *imgBack = IMGNAMED(@"btn_back.png");
        UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
        back.exclusiveTouch = YES;
        back.frame = CGRectMake(10, floorf((_bottomImageView.bounds.size.height-imgBack.size.height)/2), imgBack.size.width, imgBack.size.height);
        [back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        [_bottomImageView addSubview:back];
        
        [back setBackgroundImage:IMGNAMED(@"btn_back.png") forState:UIControlStateNormal];
        [back setBackgroundImage:IMGNAMED(@"btn_back_light.png") forState:UIControlStateHighlighted];
        [self.view addSubview:_bottomImageView];
    }
    return _bottomImageView;
}


- (UIActivityIndicatorView *)indicatorView{
    if (!_indicatorView) {
        _indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _indicatorView.hidesWhenStopped = YES;
    }
    return _indicatorView;
}

- (NSMutableArray *)datasource{
    if (!_datasource) {
        _datasource = [[NSMutableArray alloc] initWithCapacity:20];
    }
    return _datasource;
}
- (LolayGridView *)gridView{
    if (!_gridView) {
        _gridView = [[LolayGridView alloc] initWithFrame:CGRectMake(0,
                                                                    0,
                                                                    CGRectGetWidth(self.view.bounds),
                                                                    self.view.bounds.size.height -kDefaultBottomBarHeight - _kSpaceHeight)];
        _gridView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _gridView.backgroundColor = [UIColor clearColor];
        _gridView.topBounceEnabled = YES;
        _gridView.dataDelegate = self;
        _gridView.dataSource = self;
        _gridView.delegate = self;
        _gridView.showsVerticalScrollIndicator = NO;
        _gridView.showsHorizontalScrollIndicator = NO;
        [self.view addSubview:_gridView];
    }
    return _gridView;
}

- (RefreshCell *)headerCell {
    if (!_headerCell) {
        _headerCell = [RefreshCell attachRefreshCellTo:self.gridView
                                              delegate:self
                                        arrowImageName:@"refreshcell_img_arrow.png"
                                             textColor:[UIColor getColor:@"bebfc2"]
                                        indicatorStyle:UIActivityIndicatorViewStyleGray
                                                  type:RefreshTypeRefresh];
    }
    return _headerCell;
}
- (RefreshCell *)footerCell {
    if (!_footerCell) {
        _footerCell = [RefreshCell attachRefreshCellTo:self.gridView
                                              delegate:self
                                        arrowImageName:@"refreshcell_img_arrow.png"
                                             textColor:[UIColor getColor:@"bebfc2"]
                                        indicatorStyle:UIActivityIndicatorViewStyleGray
                                                  type:RefreshTypeLoadMore];
    }
    return _footerCell;
}

@end
